package zjt.demo3;

public class cloneDemo2 {
        public static void main(String[] args) throws Exception {
            //1.复制user对象为user2，改变user2的地址属性，结果user的地址属性也改变了，复制失败，
            //这是因为我们现在实现的浅拷贝
            Address address = new Address("1号店");
            User user = new User(1,"小红",address);
            User user2 = (User)user.clone();
            user2.getAddress().setAddress("2号店");
            System.out.println(user);
            System.out.println(user2);
        }
    }
 class User implements Cloneable {
    private int id;
    private String name;
    // 当属性是自定义的引用类型时，该属性也要重写clone方法
    private Address address;

    public User(int id, String name, Address address) {
        this.id = id;
        this.name = name;
        this.address = address;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", address=" + address +
                '}';
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        //return super.clone() 默认是浅拷贝
        //下边代码是深拷贝，全部复制
        //1.复制user对象
        User user = (User) super.clone();
        //2.获得user对象的地址对象并复制一份设置到user对象
        user.setAddress((Address) user.getAddress().clone());
        return user;
    }
}
    class Address implements Cloneable {
        private String address;

        public String getAddress() {
            return address;
        }

        public void setAddress(String address) {
            this.address = address;
        }

        public Address(String address) {
            this.address = address;
        }

        @Override
        public String toString() {
            return "Address{" +
                    "address='" + address + '\'' +
                    '}';
        }

        @Override
        protected Object clone() throws CloneNotSupportedException {
            return super.clone();
        }
    }